package rpc

import (
	"MessageSendService/app/api/internal/service"
	"MessageSendService/app/api/rpc/proto"
	"MessageSendService/app/common/log"
	"MessageSendService/app/common/models"
	"MessageSendService/app/common/models/vo"
	"context"
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"net"
)

type server struct {
	proto.MessageServiceServer
}

// 发送消息的rpc请求
func (s *server) SendMessage(ctx context.Context, req *proto.MessageRequest) (*proto.Result, error) {
	fmt.Println("request:", req)
	log.GetLogger().Info("接收到请求：", zap.Any("请求", req))
	//构造发送请求结构体，调用责任链发送消息
	var batReq vo.BatchMessageRequest
	batReq.Code = req.Code
	curMessageParam := models.MessageParam{
		Receiver:  req.MessageParam.Receiver,
		Variables: req.MessageParam.Variables,
		Extra:     req.MessageParam.Extra,
	}
	batReq.MessageParamList = []models.MessageParam{curMessageParam}
	batReq.MessageTemplateId = req.MessageTemplateId
	err := service.NewSendMessageService().SendMessage(batReq)
	if err != nil {
		log.GetLogger().Error("消息发送失败", zap.Any("err", err))
		return &proto.Result{Message: "消息发送失败" + err.Error()}, nil
	}
	return &proto.Result{Message: "Hello " + req.Code}, nil
}

// 批量发送消息  todo 待完善
func (s *server) BatchSendMessage(ctx context.Context, req *proto.BatchMessageRequest) (*proto.Result, error) {
	fmt.Println("BatchRequest:", req)
	return &proto.Result{Message: "Hello " + req.Code}, nil
}

func InitGRPC() {
	listen, err := net.Listen("tcp", "localhost:8089")
	if err != nil {
		fmt.Printf("failed to listen: %v", err)
		return
	}
	s := grpc.NewServer()
	proto.RegisterMessageServiceServer(s, &server{})

	defer func() {
		s.Stop()
		listen.Close()
	}()

	fmt.Println("Serving 8089...")
	err = s.Serve(listen)
	if err != nil {
		fmt.Printf("failed to serve: %v", err)
		return
	}
}
